package com.ruoyi.entwechat.controller;


import cn.hutool.core.lang.Assert;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.entwechat.common.CommonValue;
import com.ruoyi.entwechat.util.EntWeChatUtil;
import com.ruoyi.system.service.ISysConfigService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.LinkedHashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/ent/wechat")
public class EntWeChatController extends BaseController {

    private ISysConfigService iSysConfigService;

    @Autowired
    public void setiSysConfigService(ISysConfigService iSysConfigService) {
        this.iSysConfigService = iSysConfigService;
    }

    /**
     * 登录
     *
     * @param code code
     * @return ajax
     */
    @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    @Anonymous
    public R<Map<String, Object>> loginByWeChat(@RequestParam(value = "code") String code) {
        Assert.notBlank(code, () -> new ServiceException("参数不能为空!"));
        String corpId = iSysConfigService.selectConfigByKey(CommonValue.ENT_WE_CHAT_CORP_ID);
        String appSecret = iSysConfigService.selectConfigByKey(CommonValue.ENT_WE_CHAT_APP_SECRET);
        Assert.isTrue(StringUtils.isNoneBlank(corpId, appSecret), () -> new ServiceException("登录失败,参数配置错误"));
        String accessToken = EntWeChatUtil.getAccessToken(corpId, appSecret);
        Assert.notBlank(accessToken, () -> new ServiceException("获取企微授权失败!"));
        String entWxUserId = EntWeChatUtil.getUserIdByCode(accessToken, code);
        Assert.notBlank(entWxUserId, () -> new ServiceException("登录失败,票据未成功兑换用户信息!"));
        Map<String, Object> stringObjectMap = new LinkedHashMap<>();
        stringObjectMap.put("entWxUserId", entWxUserId);
        return R.ok(stringObjectMap, "登录成功");
    }

}
